layui.use(['treeSelector', 'form', 'laytpl','layer','tools'], function(){
    var $ = layui.jquery,
        form = layui.form(),
        laytpl = layui.laytpl,
        layedit = layui.layedit,
        layer = layui.layer,
        layerCategoryIndex;
    layui.treeSelector({
        elem:'#category-tree',
        type:'radio',
        categoryType:1,
        callback:function(id){
            var spanHtml = $('.add-category>span').html();
            $('.category-select>span').html(spanHtml);
            $('input[name="search[categroy_select_id]"]').val(id);
            layer.close(layerCategoryIndex);
        }
    });
    $(".category-select").click(function(){
        $(".add-category").click();
        layerCategoryIndex = layer.open({
            type: 1,
            title: false,
            closeBtn: 1,
            area: '516px',
            shadeClose: true,
            content: $('#category-content')
        });
    });
    $(".search-button").click(function(){
        $("form.search-from").submit();
    });
});

/**
 * 设置默认规格
 */
function setDefaultSku(obj, pid, gid){
    var _this = obj;
    layui.use(['layer'], function(){
       var $ = layui.jquery;
       var data = {pid: pid, gid: gid};
       $.getJSON('/product/setDefatultSku', data, function(e){
           $('input[name="default-sku-'+ pid +'"]').prop('checked', false);
           $(_this).prop('checked', true);
           layer.msg(e.msg);
       });
    });
}

/**
 * 产品批量选中
 * @param {Object} nameVal
 */
function selectAll(nameVal){
    layui.use(['layer'], function(){
        var $ = layui.jquery;
        //获取复选框的form对象
        var formObj = $("input:checkbox[name='"+nameVal+"']");
        //根据form缓存数据判断批量全选方式
        if(formObj.data('selectType') == '' || formObj.data('selectType') == undefined){
            $("input:checkbox[name='"+nameVal+"']:not(:checked)").prop('checked',true);
            formObj.data('selectType','all');
        }else{
            $("input:checkbox[name='"+nameVal+"']").prop('checked',false);
            formObj.data('selectType','');
        }
    });
}
/**
 * 修改产品排序
 * @param {Object} gid
 * @param {Object} obj
 */
function changeSort(gid,obj){
    layui.use(['jquery'], function(){
        var $ = layui.jquery;
        var selectedValue = obj.value;
        $.getJSON("/product/changeSort/",{"id":gid,"sort":selectedValue}, function(e){
            layer.msg(e.msg);
        });
    });
}
/**
 * 产品批量删除
 */
function goods_del(){
    layui.use(['layer'], function(){
        var $ = layui.jquery,
            layer = layui.layer;
        var $idObj = $('input:checkbox[name="id[]"]:checked'),gid=[];
        if($idObj.length > 0)
        {
            layer.confirm('确定要删除所选中的商品吗?', function(index){
                $idObj.each(function(){
                    gid.push($(this).val());
                });
                $.getJSON("/product/deleteProduct/", {"id":gid}, function(data){
                    window.location.reload();
                    layer.close(index);
                });
            });
        }
        else
        {
            alert('请选择要删除的数据!');
            return false;
        }
    });
}
/**
 * 产品单个删除
 */
function delete_goods(gid){
    layui.use(['layer'], function(){
        var $ = layui.jquery,
            layer = layui.layer;
        layer.confirm('确定要删除该商品吗?', function(index){
            $.getJSON("/product/deleteProduct/",{"id":gid},function(data){
                window.location.reload();
                layer.close(index);
            });
        });
    });
}

/**
 * 产品设置是否为备货商品
 */
function changeIsStock(pid, obj){
    layui.use(['jquery'], function(){
       var $ = layui.jquery;
        var selectedValue = $(obj).find('option:selected').val();
        $.getJSON('/product/changeStock/', {'id': pid, 'status': selectedValue}, function(e){
            layer.msg(e.msg);
        });
    });
}

/**
 * 单个产品上下架
 * @param {Object} pid
 * @param {Object} obj
 */
function changeIsShelf(pid,obj,target){
    layui.use(['jquery'], function(){
        var $ = layui.jquery;
        var selectedValue = $(obj).find('option:selected').val();
        if(target == 'self') {
            $('tr.sku_' + pid).each(function () {
                var _this = $(this).find('select');
                var gid = $(_this).attr('data-gid');
                _this.val(selectedValue);
                changeSkuAttr(gid, _this, 'shelf', 'blank');
            });
        }
        $.getJSON("/product/changeShelf/",{"id":pid,"type":selectedValue});
    });
}
/**
 *
 * @param gid goods_id
 * @param obj	obj
 */
function changeSkuAttr(gid,obj,type,target){
    layui.use(['jquery'], function(){
        var $ = layui.jquery;
        switch (type) {
            case 'shelf':
                var selectedValue = $(obj).find('option:selected').val();
                var url = "/product/changeGoodsShelf/";
                var data = {"id": gid, "type": selectedValue};
                if(target == 'self'){
                    var pid = $(obj).attr('data-id');
                    var shelfOnLen = $('.sku_' + pid).find('option:selected[value="1"]').length;
                    if(shelfOnLen == 0){//全部下架
                        $('.pro_' + pid).find('select').val(0);
                        changeIsShelf(pid, $('.pro_' + pid).find('select'), 'blank');
                    } else if(shelfOnLen == 1){//如果sku全部为全下架状态时候，当上架一个sku,就将商品上架
                        $('.pro_' + pid).find('select').val(1);
                        changeIsShelf(pid, $('.pro_' + pid).find('select'), 'blank');
                    } else { //全部上架
                        $('.pro_' + pid).find('select').val(1);
                        changeIsShelf(pid, $('.pro_' + pid).find('select'), 'blank');
                    }
                }
                break;
            case 'price':
                var price = $(obj).val();
                var url = "/product/changeGoodsPrice/";
                var data = {"id": gid, "price": price}
                break;
            case 'vip_price':
                var price = $(obj).val();
                var url = "/product/changeGoodsVipPrice/";
                var data = {"id": gid, "price": price}
                break;
            case 'store':
                var store = $(obj).val();
                var url = "/product/changeGoodsStore/";
                var data = {"id": gid, "store": store}
                break;
            case 'precise':
                var precise = $(obj).val();
                var url = "/product/changeGoodsPrecise/";
                var data = {"id": gid, "precise": precise}
                break;
        }
        $.getJSON(url, data, function(e){
            layer.msg(e.msg);
        });
    });
}
/**
 * 产品批量上下架
 * @param {Object} type
 */
function goods_shelf(type){
    layui.use(['jquery'], function(){
        var $ = layui.jquery;
        var $idObj = $('input:checkbox[name="id[]"]:checked'),gid=[];
        if($idObj.length > 0){
            $idObj.each(function(){
                gid.push($(this).val());
            });
            $.getJSON("/product/changeShelf/",{"id":gid,"type":type},function(data){
                window.location.reload();
            });
        }else{
            layer.msg('请选择要操作的商品!');
            return false;
        }
    });
}
function quickEdit(gid,typeVal){
    layui.use(['laytpl','layer'], function(){
        var $ = layui.jquery,
            laytpl = layui.laytpl,
            layer = layui.layer,
            submitUrl    = "",
            templateName = "",
            freshArea    = "",
            getTpl = "";

        switch(typeVal){
            case "store":
            {
                submitUrl    = "/product/update_store";
                getTpl = goodsStoreTemplate.innerHTML;
                freshArea    = "storeText";
            }
                break;

            case "price":
            {
                submitUrl    = "/product/update_price";
                getTpl = goodsPriceTemplate.innerHTML;
                freshArea    = "priceText";
            }
                break;
        }

        $.getJSON("/product/productGoods/" + gid,function(data){
            if(data.success = true && typeof(data.data) == 'object'){
                var d = {productId:gid,list:data.data.goodsList};
                //创建货品数据表格
                laytpl(getTpl).render(d, function(html){
                    layer.config({
                        extend: 'myskin/style.css'
                    });
                    layer.open({
                        type: 1,
                        title: false,
                        closeBtn: 1,
                        area: '900px',
                        skin: 'myskin',
                        shadeClose: true,
                        content: html,
                        btn: ['保存'],
                        yes: function(index, layero){
                            var formObj = document.forms['quickEditForm'];
                            $.getJSON(submitUrl,$(formObj).serialize(),function(content){
                                $("#"+freshArea+gid).html('<span class="layui-icon">&#xe642;</span>' + content.data);
                                layer.close(index);
                            });
                        }
                    });
                });
            }
        });
    });
}